requirejs.config({
    paths: {
        vue: "backend/shopro/common/vue"
    }
})
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function ($, undefined, Backend, Table, Form, Vue) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shopro/goods/index' + location.search,
                    add_url: 'shopro/goods/add',
                    edit_url: 'shopro/goods/edit',
                    del_url: 'shopro/goods/del',
                    multi_url: 'shopro/goods/multi',
                    table: 'shopro_goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        // {
                        //     field: 'type',
                        //     title: __('Type'),
                        //     searchList: {"normal": __('Type normal'), "virtual": __('Type virtual')},
                        //     formatter: Table.api.formatter.normal
                        // },
                        {
                            field: 'image',
                            title: __('Image'),
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image
                        },
                        {field: 'title', title: __('Title')},
                        // {field: 'category_ids', title: __('Category_ids')},


                        {field: 'price', title: __('Price')},
                        {field: 'likes', title: __('Likes')},
                        {field: 'views', title: __('Views')},
                        {field: 'sales', title: __('Sales')},
                        // {
                        //     field: 'dispatch_type',
                        //     title: __('Dispatch_type'),
                        //     searchList: {
                        //         "express": __('Dispatch_type express'),
                        //         "selfetch": __('Dispatch_type selfetch'),
                        //         "store": __('Dispatch_type store')
                        //     },
                        //     operate: 'FIND_IN_SET',
                        //     formatter: Table.api.formatter.label
                        // },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },

                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {
                                "up": __('Status up'),
                                "hidden": __('Status hidden'),
                                "down": __('Status down')
                            },
                            formatter: Table.api.formatter.status
                        },
                        {field: 'weigh', title: __('Weigh')},

                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shopro/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'shopro/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'shopro/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $(document).on('click', '.goods-type', function () {
                $(".goods-type").removeClass('goods-type-select');
                $(this).addClass('goods-type-select');
                let type = $(this)[0].dataset.type;
                $("#goods-type-name").val(type)

            })
            //vue Sku添加页 添加规格和价格数据
            var vue = new Vue({
                el: "#skuPrce",
                data() {
                    return {
                        skuList: [],
                        skuPrice: [],
                        skuListData: '',
                        skuPriceData: '',
                        skuModal: '',
                        childrenModal: [],
                        countId: 1,
                        allChildrenSku: [],
                        allEditSkuName:'',
                    }
                },
                mounted() {
                },
                methods: {
                    //添加主规格
                    addMainSku() {
                        if (this.skuModal !== '') {
                            this.skuList.push({
                                id: this.countId,
                                name: this.skuModal,
                                pid: 0,
                                children: []
                            })
                            this.countId ++;
                            this.skuModal = '';
                            this.buildSkuPriceTable()
                        }



                    },
                    //添加子规格
                    addChildrenSku(k) {
                        if (this.childrenModal[k] !== '') {
                            this.skuList[k].children.push({
                                id: this.countId,
                                name: this.childrenModal[k],
                                pid: this.skuList[k].id,
                            })
                            console.log(this.allChildrenSku);
                            this.$set(this.allChildrenSku,this.countId,this.childrenModal[k])

                            this.childrenModal[k] = '';

                            this.countId ++;

                            this.buildSkuPriceTable()

                        }

                    },
                    //删除主规格
                    deleteMainSku(k){
                        this.skuList.splice(k,1)
                        this.skuPrice.forEach(item=>{
                            item.goods_sku_text.splice(k,1)
                        })
                        if(this.skuList.length<=0){
                            this.skuPrice=[]
                        }
                        this.buildSkuPriceTable()
                    },
                    //删除子规格
                    deleteChildrenSku(k,i){
                        let data=this.skuList[k].children[i]
                    this.skuList[k].children.splice(i,1)
                    this.skuPrice.forEach((item,index)=>{
                        item.goods_sku_text.forEach((e,i)=>{
                            if(e==data.name){
                                this.skuPrice.splice(index,1)
                            }
                        })

                    })
                    if(this.skuList.length<=0){
                        this.skuPrice=[]
                    }
                    this.buildSkuPriceTable()
                    },
                    editStatus(i){
                        if(this.skuPrice[i].status=='up'){
                            this.skuPrice[i].status='down'
                        }else{
                            this.skuPrice[i].status='up'
                        }

                    },
                    //组合新的规格价格库存重量编码图片
                    buildSkuPriceTable() {
                        let arr = [];
                        //遍历sku子规格生成新数组，然后执行递归笛卡尔积
                        this.skuList.forEach((s1, k1) => {
                            let children = s1.children;
                            // if(children.length<1){
                            //     alert("请完善子规格");
                            //     throw 'stop';

                            // }
                            let childrenIdArray = [];
                            children.forEach((s2, k2) => {
                                childrenIdArray.push(s2.id);
                            })
                            arr.push(childrenIdArray);

                        })
                        this.skuPrice=[]
                        this.recursionSku(arr, 0 ,[]);


                    },
                    //递归找笛卡尔规格集合
                    recursionSku(arr, k, temp) {
                        if (k == arr.length) {
                            let tempDetail=[]

                            temp.forEach((item,index)=>{
                                tempDetail.push(this.allChildrenSku[item])

                            })
                            this.skuPrice.push({
                                id: this.skuPrice.length +1,
                                goods_sku_ids: temp.join(','),
                                goods_id: 0,
                                weigh: 0,
                                image: '',
                                stock: 0,
                                price:0,
                                sn: '',
                                weight: 0,
                                status: 'up',
                                goods_sku_text:tempDetail
                            });
                            return;
                        }
                        for (let i = 0; i < arr[k].length; i++) {
                            temp[k] = arr[k][i]
                            this.recursionSku(arr, k + 1, temp)
                        }
                    },
                    allEdit(type){
                        switch(type){
                            case "price":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一价格:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                                case "stock":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一库存:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                                case "weight":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一重量:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                                case "sn":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一编码:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;

                        }
                    }
                },
            })
            $(document).on("click",".all-edit-btn",function(){
                var data=vue.$data.skuPrice
                data.map(item=>{
                    item[vue.$data.allEditSkuName]=$("#allEditSkuValue").val()
                })
                Layer.closeAll();
                vue.$data.allEditSkuName=""
            })
            $(document).on("click", ".choosePicture", function () {
                var that = this;
                var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
                parent.Fast.api.open("general/attachment/select?multiple=" + multiple, "选择图片", {
                    callback: function (data) {
                        let index = $(that).attr("data-index")
                        vue.$data.skuPrice[index].image = data.url

                    }
                });
                return false;
            })

            //为了性能考虑,特意加阻断事件，拼接表单数据
            $(document).on("click", "#submitBtn", function(){
                vue.$data.skuListData = JSON.stringify(vue.$data.skuList);
                vue.$data.skuPriceData = JSON.stringify(vue.$data.skuPrice);
                var that = this;
                Layer.confirm('确认提交吗(提交之后，规格不可修改)', {
                    btn: ['确认','取消'] //按钮
                }, function(){

                    $(that).closest("form").trigger("submit");
                    return true;
                }, function(){
                    Layer.closeAll();
                    return false;
                });
            });

            Controller.api.bindevent();

        },
        edit: function () {
            $(document).on('click', '.goods-type', function () {
                $(".goods-type").removeClass('goods-type-select');
                $(this).addClass('goods-type-select');

                let type = $(this)[0].dataset.type;
                $("#goods-type-name").val(type)

            })
            //vue Sku编辑页 只能修改表单数据
            //vue Sku添加页 添加规格和价格数据
            var vue = new Vue({
                el: "#skuPrce",
                data() {
                    return {
                        skuList: Config.skuList,
                        skuPrice: Config.skuPrice,
                        is_set:0,
                        skuListData: '',
                        skuPriceData: '',
                        skuModal: '',
                        childrenModal: [],
                        countId: 1,
                        allChildrenSku: [],
                        allEditSkuName:'',
                    }
                },
                mounted() {
                    //console.log(this.skuList);
                    this.allChildrenSkuF()
                },
                methods: {
                    allChildrenSkuF(){
                        this.allChildrenSku = [];
                        for(let i=0;i<this.skuList.length;i++){
                            for(let y=0;y<this.skuList[i].children.length;y++){
                                this.allChildrenSku.push(this.skuList[i].children[y].name)
                            }

                        }
                            //console.log(this.allChildrenSku)
                    },
                    //添加主规格
                    addMainSku() {
                        if (this.skuModal !== '') {
                            this.skuList.push({
                                id: this.countId,
                                name: this.skuModal,
                                pid: 0,
                                children: []
                            });
                            this.allChildrenSkuF();
                            this.countId ++;
                            this.skuModal = '';
                            this.buildSkuPriceTable()
                        }


                    },
                    //添加子规格
                    addChildrenSku(k) {
                        if (this.childrenModal[k] !== '') {
                            this.skuList[k].children.push({
                                id: this.countId,
                                name: this.childrenModal[k],
                                pid: this.skuList[k].id,
                            });
                            this.$set(this.allChildrenSku,this.countId,this.childrenModal[k]);

                            this.allChildrenSkuF();

                            this.childrenModal[k] = '';

                            this.countId ++;

                            this.buildSkuPriceTable();

                        }

                    },
                    //删除主规格
                    deleteMainSku(k){
                        this.skuList.splice(k,1)
                        this.skuPrice.forEach(item=>{
                            item.goods_sku_text.splice(k,1)
                    })
                        if(this.skuList.length<=0){
                            this.skuPrice=[]
                        }
                        this.buildSkuPriceTable()
                    },
                    //删除子规格
                    deleteChildrenSku(k,i){
                        let data=this.skuList[k].children[i]
                        this.skuList[k].children.splice(i,1)
                        this.skuPrice.forEach((item,index)=>{
                            item.goods_sku_text.forEach((e,i)=>{
                            if(e==data.name){
                            this.skuPrice.splice(index,1)
                        }
                    })

                    })
                        if(this.skuList.length<=0){
                            this.skuPrice=[]
                        }
                        this.buildSkuPriceTable()
                    },
                    editStatus(i){
                        if(this.skuPrice[i].status=='up'){
                            this.skuPrice[i].status='down'
                        }else{
                            this.skuPrice[i].status='up'
                        }

                    },
                    //组合新的规格价格库存重量编码图片
                    buildSkuPriceTable() {
                        let arr = [];
                        let countId_p = 0;
                        //遍历sku子规格生成新数组，然后执行递归笛卡尔积
                        this.skuList.forEach((s1, k1) => {
                            let children = s1.children;
                        // if(children.length<1){
                        //     alert("请完善子规格");
                        //     throw 'stop';

                        // }
                            let childrenIdArray = [];
                            children.forEach((s2, k2) => {
                                childrenIdArray.push(countId_p);
                                countId_p ++;
                                //childrenIdArray.push(s2.id);
                            })
                            arr.push(childrenIdArray);
                         })
                        this.skuPrice=[];
                        this.recursionSku(arr, 0 ,[]);
                        this.newSkuList();
                    },
                    //递归找笛卡尔规格集合
                    recursionSku(arr, k, temp) {
                        //console.log(arr);
                        //console.log(this.allChildrenSku)
                        //console.log(k)
                        if (k == arr.length) {
                            let tempDetail=[];
                            temp.forEach((item,index)=>{
                                tempDetail.push(this.allChildrenSku[item])
                            });
                            //console.log(temp);
                            this.skuPrice.push({
                                id: this.skuPrice.length +1,
                                goods_sku_ids: temp.join(','),
                                goods_id: 0,
                                weigh: 0,
                                image: '',
                                stock: 0,
                                price:0,
                                sn: '',
                                weight: 0,
                                status: 'up',
                                goods_sku_text:tempDetail
                            });
                            this.is_set = 1;
                            return;
                        }
                        for (let i = 0; i < arr[k].length; i++) {
                            temp[k] = arr[k][i]
                            this.recursionSku(arr, k + 1, temp)
                        }
                    },
                    //重新制表
                    newskuPrice(){

                        var arr = [];

                        for(let i = 0;i < this.skuPrice.length;i++){
                            var str = [];
                            for(let p of this.skuPrice[i].goods_sku_text){
                                for(let x = 0;x < this.skuList.length;x++){
                                    for(let y = 0;y < this.skuList[x].children.length;y++){
                                        if(p == this.skuList[x].children[y].name){
                                            str.push(this.skuList[x].children[y].id)

                                        }
                                    }
                                }

                            }
                            console.log(str);
                            this.skuPrice[i].goods_sku_ids = str.join(",")
                        }
                        console.log(this.skuPrice);

                    },
                    //重新制表
                    newSkuList(){
                        let countId_fin = 1;
                        this.skuList.forEach((item1, index1) => {
                            this.skuList[index1].id = countId_fin;
                            countId_fin++ ;
                            let children = item1.children;
                            children.forEach((item2, index2) => {
                                this.skuList[index1].children[index2].id = countId_fin;
                                countId_fin ++;
                            })
                        })
                        console.log(this.skuList);
                        this.newskuPrice()
                    },
                    allEdit(type){
                        switch(type){
                            case "price":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一价格:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                            case "stock":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一库存:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                            case "weight":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一重量:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;
                            case "sn":
                                this.allEditSkuName=type
                                layer.open({
                                    type: 1,
                                    area: ['350px', '200px'],
                                    shadeClose: false, //点击遮罩关闭
                                    content: `<div style="display: flex;
                                    flex-direction: column;padding:20px">
                                <p><span>请输入统一编码:</span><input type="text" id="allEditSkuValue" /></p>
                                <button class="btn btn-success all-edit-btn">确定</button>
                                    </div>`
                                });
                                break;

                        }
                    }
                },
            })
            $(document).on("click",".all-edit-btn",function(){
                var data=vue.$data.skuPrice
                data.map(item=>{
                    item[vue.$data.allEditSkuName]=$("#allEditSkuValue").val()
                })
                Layer.closeAll();
                vue.$data.allEditSkuName=""
            })
            $(document).on("click", ".choosePicture", function () {
                var that = this;
                var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
                parent.Fast.api.open("general/attachment/select?multiple=" + multiple, "选择图片", {
                    callback: function (data) {
                        let index = $(that).attr("data-index")
                        vue.$data.skuPrice[index].image = data.url

                    }
                });
                return false;
            })

            //为了性能考虑,特意加阻断事件，拼接表单数据
            $(document).on("click", "#submitBtn", function(){
                vue.$data.skuListData = JSON.stringify(vue.$data.skuList);
                vue.$data.skuPriceData = JSON.stringify(vue.$data.skuPrice);
                var that = this;
                Layer.confirm('确认提交吗', {
                    btn: ['确认','取消'] //按钮
                }, function(){
                    $(that).closest("form").trigger("submit");
                    return true;
                }, function(){
                    Layer.closeAll();
                    return false;
                });
            });
            $('.tooltip-toggle').tooltip('toggle');
            Controller.api.bindevent();
        },
        select: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shopro/goods/index',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                showToggle: false,
                showExport: false,
                columns: [
                    [
                        {field: 'state', checkbox: true,},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var multiple = Backend.api.query('multiple');
                                    multiple = multiple == 'true' ? true : false;
                                    row.ids=row.id.toString()
                                    Fast.api.close({data: row, multiple: multiple});
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        }
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var goodsIdArr = new Array();
                if(Backend.api.query('type')=='activity'){
                    $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                        goodsIdArr.push(j);
                    });
                    var multiple = Backend.api.query('multiple');
                    multiple = multiple == 'true' ? true : false;
                    Fast.api.close({data: goodsIdArr, multiple: multiple});
                }else{
                    let row={}
                    $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                        row=j
                        goodsIdArr.push(j.id);
                    });
                    var multiple = Backend.api.query('multiple');
                    multiple = multiple == 'true' ? true : false;
                    row.ids=goodsIdArr.join(",")
                    Fast.api.close({data: row, multiple: multiple});
                }

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
             //绑定TAB事件
             $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                // var options = table.bootstrapTable(tableOptions);
                var typeStr = $(this).attr("href").replace('#', '');
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    // params.filter = JSON.stringify({type: typeStr});
                    params.type = typeStr;

                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;

            });
            require(['upload'], function (Upload) {
                Upload.api.plupload($("#toolbar .plupload"), function () {
                    $(".btn-refresh").trigger("click");
                });
            });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});